package aliyun

import (
	"fmt"

	"gitee.com/infraboard/go-course/day8/cloudstation/store"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/go-playground/validator/v10"
)

type aliyun struct {
	Endpint   string `validate:"required"`
	AcessKey  string `validate:"required"`
	SecretKey string `validate:"required"`
	listener  oss.ProgressListener
}

var validate = validator.New()

func (a *aliyun) validate() error {
	return validate.Struct(a)
}

func (a *aliyun) UploadFile(bucketName, objectKey, localFilePath string) error {
	//创建一个oss的对象并获取到客户端
	client, err := oss.New(a.Endpint, a.AcessKey, a.SecretKey)
	if err != nil {
		return err
	}
	//传入bucket的名字
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		return err
	}
	//开始从文件中推送对象
	err = bucket.PutObjectFromFile("log_parking/mxg/"+localFilePath, localFilePath, oss.Progress(a.listener))
	if err != nil {
		return err
	}
	//打印下载url
	downUrl, err := bucket.SignURL("log_parking/mxg/"+localFilePath, oss.HTTPGet, 60*60*24)
	if err != nil {
		return fmt.Errorf("sign file download url error,%s", err)
	}
	fmt.Printf("下载链接: %s\n", downUrl)
	fmt.Println("\n注意: 文件下载有效期为1天, 中转站保存时间为3天, 请及时下载")

	return nil
}
func NewUploader(endpint, acessKey, secretKey string) (store.Uploader, error) {
	uploader := &aliyun{
		Endpint:   endpint,
		AcessKey:  acessKey,
		SecretKey: secretKey,
		listener:  NewListener(),
	}
	if err := uploader.validate(); err != nil {
		return nil, err
	}
	return uploader, nil
}
